package com.jt.demos;

import redis.clients.jedis.Jedis;

import java.util.Map;

/**
 * 基于redis存储商品购物车信息
 */
public class CartDemo01 {

    public static void addCart(Long userId,Long productdId,int num) {
        Jedis jedis = new Jedis("192.168.126.129",6379);
        //添加商品到购物车
        String product = jedis.hget("cart:"+userId, String.valueOf(productdId));
        //添加数量 hincyBy函数在key不存在时自动创建key
        jedis.hincrBy("cart:"+userId, String.valueOf(productdId), num);
        jedis.close();
    }

    public static Map<String,String> listCart(Long userId){
        Jedis jedis = new Jedis("192.168.126.129",6379);
        //查看购物车商品
        Map<String, String> map = jedis.hgetAll("cart:" + userId);
        jedis.close();
        return map;
    }

    public static void main(String[] args) {
        //1. 添加商品到购物车
        addCart(1L, 101L, 1);
        addCart(1L, 201L, 1);
        addCart(1L, 101L, 1);
        addCart(2L, 101L, 1);
        //2. 查看购物车
        Map<String, String> map = listCart(1L);
        System.out.println(map);
    }
}
